<template>
  <div class="kefu-page">
    <div class="header">
      <div class="title">客服对话</div>
      <div class="reply-target">
        <span class="label">回复对象</span>
        <input class="target-input" v-model="targetUser" placeholder="请输入要回复的用户名" />
        <span class="status" :class="{ online: isConnected }">
          {{ isConnected ? '已连接' : '未连接' }}
        </span>
      </div>
    </div>

    <div class="chat-box" ref="chatBox">
      <div v-for="(msg, idx) in messages" :key="idx" class="msg" :class="{ self: msg.self }">
        <div class="bubble">
          <div class="meta">
            <span class="from">{{ msg.self ? '我（客服）' : msg.from || '用户' }}</span>
            <span class="time">{{ msg.time }}</span>
          </div>
          <div class="text">{{ msg.text }}</div>
        </div>
      </div>
    </div>

    <div class="input-bar">
      <input
        v-model="draft"
        class="input"
        type="text"
        placeholder="输入要回复的内容，回车发送"
        @keyup.enter="send"
      />
      <button class="send-btn" :disabled="!isConnected || !draft.trim()" @click="send">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { ensureConnected, subscribe, sendMessage as wsSend } from '@/utils/chatWs'
import useChatStore from '@/store/modules/chat'

const chatStore = useChatStore()

const messages = ref([])
const draft = ref('')
const chatBox = ref(null)
const isConnected = ref(false)
const targetUser = ref('')
const recentUsers = ref([])

function logMessage(text, { self = false, from = '', time = '' } = {}) {
  messages.value.push({ text, self, from, time: time || new Date().toLocaleTimeString() })
  nextTick(() => {
    if (chatBox.value) chatBox.value.scrollTop = chatBox.value.scrollHeight
  })
}

let unsubscribe = null

onMounted(() => {
  ensureConnected()
  unsubscribe = subscribe((evt) => {
    if (evt.type === 'open') isConnected.value = true
    if (evt.type === 'close') isConnected.value = false
    if (evt.type === 'message') {
      // 优先尝试解析 JSON，以便识别来源用户
      try {
        const obj = JSON.parse(evt.data)
        const from = obj.from || obj.userName || obj.user || '用户'
        const text = obj.content ?? obj.text ?? evt.data
        logMessage(String(text), { from })
        if (from && from !== '用户' && !recentUsers.value.includes(from)) {
          recentUsers.value.unshift(from)
          if (!targetUser.value) targetUser.value = from
        }
      } catch {
        // 非 JSON，无法识别来源，按匿名用户展示
        logMessage(evt.data, { from: '用户' })
      }
    }
  })
  // 进入会话页清空未读
  chatStore.clearUnread()
})

onBeforeUnmount(() => {
  if (unsubscribe) unsubscribe()
})

function send() {
  const text = draft.value.trim()
  if (!text) return
  const to = targetUser.value.trim()
  if (!to) {
    logMessage('请先在上方输入要回复的用户名', { from: '系统' })
    return
  }
  const payload = JSON.stringify({ to, content: text })
  const ok = wsSend(payload)
  if (ok) {
    logMessage(`@${to} ${text}`, { self: true, from: '我（客服）' })
    draft.value = ''
  }
}
</script>

<style scoped>
.kefu-page {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 12px;
  box-sizing: border-box;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 4px;
}
.title {
  font-size: 16px;
  font-weight: 600;
}
.reply-target { display: flex; align-items: center; gap: 8px; }
.label { font-size: 12px; color: #666; }
.target-input { height: 28px; padding: 0 8px; border: 1px solid #ddd; border-radius: 6px; }
.status {
  font-size: 12px;
  color: #999;
}
.status.online { color: #2db55d; }

.chat-box {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
  border: 1px solid #eee;
  border-radius: 6px;
}
.msg {
  display: flex;
  margin: 8px;
}
.msg.self { justify-content: flex-end; }
.bubble {
  max-width: 70%;
  background: #f5f5f5;
  border-radius: 8px;
  padding: 8px 10px;
}
.msg.self .bubble { background: #d7f5e4; }
.meta {
  display: flex;
  gap: 8px;
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}
.text { white-space: pre-wrap; word-break: break-word; }

.input-bar {
  display: flex;
  gap: 8px;
  margin-top: 10px;
}
.input {
  flex: 1;
  height: 36px;
  padding: 0 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
}
.send-btn {
  height: 36px;
  padding: 0 16px;
  border: none;
  background: #1677ff;
  color: #fff;
  border-radius: 6px;
  cursor: pointer;
}
.send-btn:disabled {
  background: #b7d2ff;
  cursor: not-allowed;
}
</style>
